<template>
  <view class="container">
    
    <Card class="filter-card">
      <view class="filter-item">
        <text class="label">关联学生</text>
        <picker 
          mode="selector" 
          :range="students" 
          @change="onStudentChange"
        >
          <view class="picker">
            {{ selectedStudent || '全部学生' }}
          </view>
        </picker>
      </view>
      
      <view class="filter-item">
        <text class="label">计划状态</text>
        <picker 
          mode="selector" 
          :range="statusOptions" 
          @change="onStatusChange"
        >
          <view class="picker">
            {{ selectedStatus || '全部状态' }}
          </view>
        </picker>
      </view>
    </Card>
    
    <Card class="search-card">
      <view class="search-box">
        <input 
          class="search-input" 
          type="text" 
          placeholder="搜索计划" 
          v-model="searchKeyword"
        />
        <Button class="search-btn" type="primary" size="small" text="搜索" />
      </view>
    </Card>
    
    <view class="plans-list">
      <uni-swipe-action>
        <uni-swipe-action-item
          v-for="(plan, index) in filteredPlans" 
          :key="plan.id" 
          :right-options="swipeOptions"
          @click="onSwipeClick(plan.id, index, $event)"
          @swiperight="handleSwipeRight(plan.id, index)"
          @swipeleft="handleSwipeLeft(plan.id, index)"
          @change="onSwipeChange($event)"
        >
          <Card 
            class="plan-card"
            clickable
            @click="goToPlanDetail(plan)"
          >
            <view class="plan-header">
              <text class="plan-title">{{ plan.title }}</text>
              <view class="plan-status" :class="plan.statusClass">
                {{ plan.status }}
              </view>
            </view>
            <view class="plan-content">
              <view class="plan-info">
                <text class="info-label">关联学生：</text>
                <text class="info-value">{{ plan.student }}</text>
              </view>
              <view class="plan-info">
                <text class="info-label">科目：</text>
                <text class="info-value">{{ plan.subject }}</text>
              </view>
              <view class="plan-info">
                <text class="info-label">时间：</text>
                <text class="info-value">{{ plan.time }}</text>
              </view>
              <view class="plan-info">
                <text class="info-label">创建时间：</text>
                <text class="info-value">{{ plan.createTime }}</text>
              </view>
            </view>
          </Card>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </view>
    
    <Button 
      class="add-btn" 
      type="primary" 
      text="创建学习计划" 
      @click="goToCreatePlan"
    />
  </view>
</template>

<script>
import uniSwipeAction from '@/uni_modules/uni-swipe-action/components/uni-swipe-action/uni-swipe-action.vue'
import uniSwipeActionItem from '@/uni_modules/uni-swipe-action/components/uni-swipe-action-item/uni-swipe-action-item.vue'

export default {
  components: {
    uniSwipeAction,
    uniSwipeActionItem
  },
  data() {
    console.log('Components registered');
    return {
      searchKeyword: '',
      students: ['全部学生', '张小明', '李小红', '王小刚'],
      selectedStudent: '全部学生',
      statusOptions: ['全部状态', '已发布', '未发布', '已暂停'],
      selectedStatus: '全部状态',
      plans: [
        {
          id: '1',
          title: '数学每日练习',
          student: '张小明',
          subject: '数学',
          time: '每天 19:00-20:00',
          createTime: '2025.08.25',
          status: '已发布',
          statusClass: 'status-published'
        },
        {
          id: '2',
          title: '英语单词背诵',
          student: '李小红',
          subject: '英语',
          time: '每周一、三、五 07:00-07:30',
          createTime: '2025.08.20',
          status: '已发布',
          statusClass: 'status-published'
        },
        {
          id: '3',
          title: '语文阅读理解',
          student: '王小刚',
          subject: '语文',
          time: '每周二、四 18:30-19:30',
          createTime: '2025.08.15',
          status: '未发布',
          statusClass: 'status-unpublished'
        }
      ],
      swipeOptions: [
        {
          text: '分享',
          style: {
            backgroundColor: '#ffc53d',
            color: '#fff',
            height: '100%', // 设置高度为100%以匹配卡片高度
            display: 'flex', // 使用flex布局
            alignItems: 'center', // 垂直居中
            justifyContent: 'center' // 水平居中
          }
        },
        {
          text: '删除',
          style: {
            backgroundColor: '#ff5a5f',
            color: '#fff',
            height: '100%', // 设置高度为100%以匹配卡片高度
            display: 'flex', // 使用flex布局
            alignItems: 'center', // 垂直居中
            justifyContent: 'center' // 水平居中
          }
        }
      ]
    };
  },
  
  computed: {
    filteredPlans() {
      let result = this.plans;
      
      // 根据学生筛选
      if (this.selectedStudent !== '全部学生') {
        result = result.filter(plan => plan.student === this.selectedStudent);
      }
      
      // 根据状态筛选
      if (this.selectedStatus !== '全部状态') {
        result = result.filter(plan => plan.status === this.selectedStatus);
      }
      
      // 根据关键词搜索
      if (this.searchKeyword) {
        result = result.filter(plan => 
          plan.title.includes(this.searchKeyword) || 
          plan.student.includes(this.searchKeyword) ||
          plan.subject.includes(this.searchKeyword)
        );
      }
      
      return result;
    }
  },
  
  methods: {
    onStudentChange(e) {
      this.selectedStudent = this.students[e.detail.value];
    },
    
    onStatusChange(e) {
      this.selectedStatus = this.statusOptions[e.detail.value];
    },
    
    goToCreatePlan() {
      uni.navigateTo({
        url: '/pages/plan/create'
      });
    },
    
    goToPlanDetail(plan) {
      uni.navigateTo({
        url: '/pages/plan/detail?id=' + plan.id
      });
    },
    
    onDeleteClick(planId, index, event) {
      console.log('deletePlan function called with planId:', planId, 'index:', index);
      console.log('Event details:', {
        type: event.type,
        target: event.target,
        timestamp: new Date().toISOString()
      });
      
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个学习计划吗？此操作不可恢复。',
        success: (res) => {
          console.log('Modal result:', res);
          if (res.confirm) {
            console.log('User confirmed deletion at timestamp:', new Date().toISOString());
            // 从计划列表中移除
            const planIndex = this.plans.findIndex(p => p.id === planId);
            console.log('Plan index to delete:', planIndex);
            
            if (planIndex !== -1) {
              const deletedPlan = this.plans[planIndex];
              this.plans.splice(planIndex, 1);
              
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              console.log('Plan deleted successfully:', {
                id: deletedPlan.id,
                title: deletedPlan.title,
                student: deletedPlan.student,
                timestamp: new Date().toISOString()
              });
            } else {
              console.log('Plan not found in array at timestamp:', new Date().toISOString());
            }
          } else {
            console.log('User cancelled deletion at timestamp:', new Date().toISOString());
          }
        },
        fail: (error) => {
          console.error('Modal failed:', error);
          console.error('Error details:', {
            code: error.errno,
            message: error.errmsg,
            timestamp: new Date().toISOString()
          });
        }
      });
    },
    
    onSwipeChange(event) {
      console.log('Swipe action changed:', {
        event: event,
        timestamp: new Date().toISOString()
      });
    },
    
    handleSwipeRight(planId, index) {
      const plan = this.plans.find(p => p.id === planId);
      console.log('Swipe right detected:', {
        planId,
        index,
        planTitle: plan?.title,
        student: plan?.student,
        timestamp: new Date().toISOString()
      });
    },
    
    handleSwipeLeft(planId, index) {
      const plan = this.plans.find(p => p.id === planId);
      console.log('Swipe left detected:', {
        planId,
        index,
        planTitle: plan?.title,
        student: plan?.student,
        timestamp: new Date().toISOString()
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: $spacing-base;
  background-color: $background-color;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: $spacing-lg;
  padding: $spacing-xl 0;
}

.title {
  font-size: $font-size-xl;
  font-weight: bold;
  color: $text-primary;
  display: block;
  margin-bottom: $spacing-sm;
}

.subtitle {
  font-size: $font-size-sm;
  color: $text-secondary;
}

.filter-card {
  margin-bottom: $spacing-base;
}

.filter-item {
  margin-bottom: $spacing-base;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  display: block;
  font-size: $font-size-base;
  color: $text-primary;
  margin-bottom: $spacing-sm;
}

.picker {
  width: 100%;
  height: 80rpx;
  padding: 0 $spacing-base;
  line-height: 80rpx;
  border: 1rpx solid $text-tertiary;
  border-radius: $border-radius-base;
  font-size: $font-size-base;
  box-sizing: border-box;
}

.search-card {
  margin-bottom: $spacing-base;
}

.search-box {
  display: flex;
  flex-direction: row;
}

.search-input {
  flex: 1;
  height: 70rpx;
  padding: 0 $spacing-base;
  border: 1rpx solid $text-tertiary;
  border-radius: $border-radius-base;
  font-size: $font-size-sm;
  margin-right: $spacing-sm;
  box-sizing: border-box;
}

.search-btn {
  height: 70rpx;
}

.plans-list {
  margin-bottom: 120rpx;
  // 增加列表项之间的垂直间距
  & > .uni-swipe-action-item + .uni-swipe-action-item {
    margin-top: $spacing-lg; // 根据需要调整这个值
  }
}

.plan-card {
  margin-bottom: $spacing-xl; // 增加卡片底部的间距
}


.plan-header {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-bottom: $spacing-base;
}

.plan-title {
  font-size: $font-size-base;
  font-weight: bold;
  color: $text-primary;
  flex: 1;
}

.plan-status {
  font-size: $font-size-sm;
  padding: $spacing-xs $spacing-sm;
  border-radius: $border-radius-sm;
}

.status-published {
  background-color: rgba($secondary-color, 0.1);
  color: $secondary-color;
}

.status-unpublished {
  background-color: rgba($text-tertiary, 0.1);
  color: $text-tertiary;
}

.plan-content {
  font-size: $font-size-sm;
}

.plan-info {
  display: flex;
  flex-direction: row;
  margin-bottom: $spacing-xs;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.info-label {
  color: $text-secondary;
  width: 160rpx;
}

.info-value {
  flex: 1;
  color: $text-primary;
}

.add-btn {
  position: fixed;
  bottom: 40rpx;
  left: $spacing-base;
  right: $spacing-base;
}
</style>